#!/bin/bash

INSTALL_DIR=/opt/eclipse
WD_TMP_FILE=/tmp/watchdog
REFRESH_TIME=5
TIMEOUT_TIME=300

##############################################
# UTILITY FUNCTIONS
##############################################
# Run preRemove function and start watchdog if needed
function runPreRemove {
    if [ -f "${WD_TMP_FILE}" ]; then
        WATCHDOG_DEVICE=`cat ${WD_TMP_FILE}`
        preRemove &
        PID=$!
        START=$(date +%s)
        
        while [ -d "/proc/$PID" ]; do
            echo w > ${WATCHDOG_DEVICE}
            DELTA=$(($(date +%s) - $START))
            if [ "$DELTA" -ge "$TIMEOUT_TIME" ]; then
                echo "The installation process is not responding. It'll be stopped."
                kill -9 $PID >> /dev/null 2>&1
            fi
            sleep $REFRESH_TIME
        done
        stopWatchdog
    else
        preRemove &
        PID=$!
        START=$(date +%s)
        
        while [ -d "/proc/$PID" ]; do
            DELTA=$(($(date +%s) - $START))
            if [ "$DELTA" -ge "$TIMEOUT_TIME" ]; then
                echo "The installation process is not responding. It'll be stopped."
                kill -9 $PID >> /dev/null 2>&1
            fi
            sleep $REFRESH_TIME
        done
    fi
}

# Deactivate watchdog device if possible
function stopWatchdog {
    if [ -n "${WATCHDOG_DEVICE}" ]; then
        echo V > ${WATCHDOG_DEVICE}
    fi
}

# Pre-remove script
function preRemove {
    #Remove INIT scripts
    rm /etc/init.d/firewall
    rm /etc/init.d/kura
    update-rc.d firewall remove
    update-rc.d kura remove
    
    #Delete Eclipse directory if present
    if [ -d "${INSTALL_DIR}/kura/data" ] ; then
      rm -rf ${INSTALL_DIR}/kura/data
    fi
    
    if [ -d "${INSTALL_DIR}/kura" ] ; then
      rm -rf ${INSTALL_DIR}/kura
    fi
    
    echo ""
    echo "Uninstalling KURA... Done!"
}
##############################################
# END UTILITY FUNCTIONS
##############################################

##############################################
# PRE-REMOVE SCRIPT
##############################################
PIDS=`pgrep java`

echo ""
echo "Uninstalling KURA..."

#Kill JVM and monit for installation
if [ -f "/var/run/kura.pid" ] ; then
  KURA_PID=`cat /var/run/kura.pid`

  for pid in "${PIDS[@]}"
  do
    if [ "$KURA_PID" == "$pid" ] ; then
      `kill $pid` >> /tmp/kura_install.log 2>&1
    fi
  done
fi

runPreRemove
##############################################
# END PRE-REMOVE SCRIPT
##############################################